//
//  MYComposeViewController.swift
//  Sina
//
//  Created by 王亮龙1 on 16/5/29.
//  Copyright © 2016年 lianglong. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD

class MYComposeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.whiteColor()
        setupUI()
        
        //注册通知
        registerNotification()
    }
    
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        
        //在无图的情况下,界面出现就弹出键盘,
        if pictureSelector.images.count == 0 {
            textView.becomeFirstResponder()
        }
        
        
    }
    
    
    //懒加载子控件
    //右边导航条按钮
    private lazy var rightBarBtnItem: UIBarButtonItem = {
        let btn = UIButton()
        
        btn.setTitle("发送", forState: .Normal)
        btn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        btn.setTitleColor(UIColor.darkGrayColor(), forState: .Disabled)
        btn.titleLabel?.font = UIFont.systemFontOfSize(14)
        
        btn.setBackgroundImage(UIImage(named: "common_button_orange"), forState: .Normal)
        btn.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: .Highlighted)
        btn.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: .Disabled)
        
        btn.addTarget(self, action: #selector(MYComposeViewController.send), forControlEvents: .TouchUpInside)
        
        btn.frame = CGRect(x: 0, y: 0, width: 45, height: 30)
        
        let rightBarBtnItem = UIBarButtonItem(customView: btn)
        return rightBarBtnItem
    }()
    
    //textView
    private lazy var textView: UITextView = {
        let textV = UITextView()
        
        textV.font = UIFont.systemFontOfSize(18)
        textV.textColor = UIColor.darkGrayColor()
        //背景颜色
        textV.backgroundColor = UIColor(white: 0.8, alpha: 1)
        //设置键盘消失的方式
        textV.keyboardDismissMode = .OnDrag
        textV.alwaysBounceVertical = true
        textV.delegate = self
        
        return textV
    }()
    //占位label
    private lazy var placeHolderLabel: UILabel = UILabel(title: "一点寒芒先到,  随后枪出如龙", font: 18, textColor: UIColor.lightGrayColor())
    //toolBar
    private lazy var toolBar: UIToolbar = UIToolbar()
    //图片选择视图
    private lazy var pictureSelector: MYPictureSelectorController = MYPictureSelectorController()
    
    
    
    
    
    //MARK:注册通知
    private func registerNotification() {
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(MYComposeViewController.keyboardChange(_:)), name: UIKeyboardWillChangeFrameNotification, object: nil)
        
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    @objc private func keyboardChange(notify: NSNotification) {
        
        //获取键盘改变时时间
        let time_t = (notify.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        //获取键盘改变时rect
        let rect = (notify.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        
        //获取rect的Y
        let offsetY = -UIScreenHeight + rect.origin.y
        
        UIView.animateWithDuration(time_t, animations: { 
            
            self.toolBar.snp_updateConstraints(closure: { (make) in
                make.bottom.equalTo(offsetY)
            })
            
            }) { (_) in
                self.view.layoutIfNeeded()
        }
    }
    

}



//搭建UI
extension MYComposeViewController {
    
    //创建界面
    private func setupUI() {
    
        setupNavBar()
        setupTextView()
        setupToolBar()
        setupPictrueSelectorVC()
    }
    
    
    //设置图片选择vc
    private func setupPictrueSelectorVC() {
        
        self.addChildViewController(pictureSelector)
        self.view.addSubview(pictureSelector.view)
        //将toolbar移到最顶层
        self.view.bringSubviewToFront(toolBar)
        
        pictureSelector.view.snp_makeConstraints { (make) in
            make.left.right.bottom.equalTo(self.view)
            make.height.equalTo(0)
        }
    }
    
    //设置toolbar
    private func setupToolBar() {
        
        self.view.addSubview(toolBar)
        
        toolBar.snp_makeConstraints { (make) in
            make.left.right.bottom.equalTo(self.view)
        }
        
        var items = [UIBarButtonItem]()
        //操作数据 添加UIBarButtonItem
        let itemSettings = [["imageName": "compose_toolbar_picture","actionName": "selectPicture"],
                            ["imageName": "compose_mentionbutton_background","actionName": "selectMention"],
                            ["imageName": "compose_trendbutton_background","actionName": "selectTrend"],
                            ["imageName": "compose_emoticonbutton_background", "actionName": "selectEmoticon"],
                            ["imageName": "compose_add_background","actionName": "selectAdd"]]
        for item in itemSettings {
            
            let imageName = item["imageName"]
            let action = item["actionName"]!
            //创建item
            let item = UIBarButtonItem(imageName: imageName, title: nil, target: self, action: Selector(action))
            
            items.append(item)
            //创建弹簧
            let space = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
            items.append(space)
            
        }
        
        items.removeLast()
        toolBar.items = items
        
    }
    
    //设置textView
    private func setupTextView() {
        
        self.view.addSubview(textView)
        
        textView.snp_makeConstraints { (make) in
            make.top.left.right.equalTo(self.view)
            make.height.equalTo(UIScreenHeight / 3)
        }
        
        textView.addSubview(placeHolderLabel)
        placeHolderLabel.snp_makeConstraints { (make) in
            make.top.equalTo(textView.snp_top).offset(8)
            make.left.equalTo(textView.snp_left).offset(5)
        }
        
    }
    
    //设置navBar
    private func setupNavBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", target: self, action: #selector(MYComposeViewController.close))
        navigationItem.rightBarButtonItem = rightBarBtnItem
        //设置rightBarButtonItem交互一开始关闭
        navigationItem.rightBarButtonItem?.enabled = false
        
        let titleV = UIView(frame: CGRect(x: 0, y: 0, width: UIScreenWidth, height: 40))
        let titleLabel = UILabel(title: "发布微博", font: 16, textColor: UIColor.darkGrayColor(), alignment: .Center)
        let nameLabel = UILabel(title: MYUserAccountViewModel.shareUserAccountViewModel.userAccount?.name ?? "", font: 13, textColor: UIColor.grayColor(), alignment: .Center)
        
        titleV.addSubview(titleLabel)
        titleV.addSubview(nameLabel)
        
        titleLabel.snp_makeConstraints { (make) in
            make.centerX.equalTo(titleV.snp_centerX)
            make.top.equalTo(titleV.snp_top)
        }
        
        nameLabel.snp_makeConstraints { (make) in
            make.centerX.equalTo(titleV.snp_centerX)
            make.top.equalTo(titleLabel.snp_bottom)
        }
        
        navigationItem.titleView = titleV
        
    }
    
}


extension MYComposeViewController: UITextViewDelegate {
    
    //keyboard的代理方法
    func textViewDidChange(textView: UITextView) {
        
        placeHolderLabel.hidden = textView.hasText()
        rightBarBtnItem.enabled = textView.hasText()
    }
    
    //关闭界面跳转控制器
    @objc private func close() {
        //辞去第一响应者,退下键盘
        self.view.endEditing(true)
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    
    @objc private func send() {
        print("发送微博")
        //辞去第一响应者,退下键盘
        self.view.endEditing(true)
        
        MYNetworkingTools.shareTools.sendStatus(textView.text, images: pictureSelector.images) { (responseObject, error) in
            if error != nil {
                SVProgressHUD.showErrorWithStatus("发布微博失败")

                return
            }
            
            SVProgressHUD.showSuccessWithStatus("发布微博成功")
        }
    }
    
    
    //toolBar的btn点击方法
   @objc private func selectPicture() {
        print("选择图片")
        self.pictureSelector.view.snp_updateConstraints { (make) in
            make.height.equalTo(UIScreenHeight / 3 * 2)
        }
    
    }
    
   @objc private func selectMention() {
        print("@...")
    }
    
   @objc private func selectTrend() {
        print("#...")
    }
    
   @objc private func selectEmoticon() {
        print("选择表情")
    }
    
   @objc private func selectAdd() {
        print("+...")
    }
    
    
    
    
}
